<template>
  <el-card class="echarts-card">
    <template #header>
      <div class="card-header">
        <span>{{ chartTitle }}</span>
        <el-select v-model="timeRange" @change="handleTimeChange" size="small">
          <el-option label="近7天" value="7" />
          <el-option label="近30天" value="30" />
          <el-option label="近90天" value="90" />
        </el-select>
      </div>
    </template>
    <!-- 使用 VChart 组件（vue-echarts 提供的） -->
    <VChart
      :option="chartOption"
      :autoresize="true"
      style="width: 100%; height: 300px;"
    />
  </el-card>
</template>

<script setup>
import { ref, watch } from "vue";
import { use } from "echarts/core";
import { LineChart } from "echarts/charts";
import {
  GridComponent,
  TooltipComponent,
  LegendComponent,
  TitleComponent,
} from "echarts/components";
import { CanvasRenderer } from "echarts/renderers";
import VChart from "vue-echarts"; // 导入 vue-echarts 的组件

// 注册 ECharts 组件（vue-echarts 需要手动注册）
use([LineChart, GridComponent, TooltipComponent, LegendComponent, CanvasRenderer]);

// 图表标题
const chartTitle = ref("学校注册数统计");
// 时间范围选择
const timeRange = ref("7");
// 图表配置
const chartOption = ref({
  tooltip: {
    trigger: "axis",
    axisPointer: { type: "shadow" },
  },
  grid: {
    left: "3%",
    right: "4%",
    bottom: "3%",
    containLabel: true,
  },
  xAxis: {
    type: "category",
    data: [],
  },
  yAxis: {
    type: "value",
    name: "数量",
  },
  series: [
    {
      name: "新增学校",
      type: "line",
      data: [],
      smooth: true,
      itemStyle: { color: "#409EFF" },
      lineStyle: { width: 2 },
    },
  ],
});

// 模拟时间数据生成
const generateTimeData = (days) => {
  const dates = [];
  for (let i = days - 1; i >= 0; i--) {
    const date = new Date();
    date.setDate(date.getDate() - i);
    dates.push(`${date.getMonth() + 1}/${date.getDate()}`);
  }
  return dates;
};

// 模拟统计数据生成
const generateChartData = (days) => {
  return Array.from({ length: days }, () => Math.floor(Math.random() * 20) + 1);
};

// 处理时间范围变化
const handleTimeChange = (days) => {
  chartOption.value.xAxis.data = generateTimeData(Number(days));
  chartOption.value.series[0].data = generateChartData(Number(days));
};

// 初始化图表数据
watch(
  timeRange,
  () => {
    handleTimeChange(timeRange.value);
  },
  { immediate: true }
);
</script>

<style scoped>
.echarts-card {
  width: 98%;
  margin: 10px auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>